package cn.ewan.cloud.tenant.data.router.spring;

import cn.ewan.cloud.common.support.Log;
import cn.ewan.cloud.common.web.support.BusinessException;
import cn.ewan.cloud.tenant.data.router.core.business.config.tenant.TenantUser;
import cn.ewan.cloud.tenant.data.router.core.business.config.tenant.TenantUserManager;
import cn.ewan.cloud.tenant.data.router.core.business.plugin.request.FeignInterceptor;
import cn.ewan.cloud.tenant.data.router.core.common.exception.TenantMsgCode;
import cn.ewan.cloud.tenant.data.router.spring.build.BuildUtil;
import cn.ewan.cloud.tenant.data.router.spring.config.TenantConfig;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lgh
 * @date 2022/12/13 16:48
 */
@Configuration
@EnableConfigurationProperties(value = {TenantConfig.class})
//@ConditionalOnClass(ShardingDataSource.class)
public class TenantAutoConfiguration implements InitializingBean {


    /**
     * Feign请求拦截器
     */
    @Bean
    public RequestInterceptor feignRequestInterceptor() {
        return new FeignInterceptor();
    }


    @Bean
    public TenantUserManager tenantUserManager(TenantConfig tenantConfig) {
        Log.NORMAL.info("tenant config={}", tenantConfig);

        //检查多租户列表
        List<TenantUser> users = tenantConfig.getUsers();
        if (users == null || users.isEmpty()) {
            throw new BusinessException(TenantMsgCode.TENANT_USER_EMPTY);
        }

        //检查是否有配置不完整的多租户
        List<TenantUser> configErrorTenantUser = users.stream()
                .filter(x -> StringUtils.isBlank(x.getTenant())).collect(Collectors.toList());
        if (!configErrorTenantUser.isEmpty()) {
            throw new BusinessException(TenantMsgCode.TENANT_USER_CONFIG_EMPTY);
        }

        //存到TenantUserManager
        TenantUserManager userManager = new TenantUserManager();
        userManager.setUsers(users);
        return userManager;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String buildTime = new BuildUtil().logBuildTime();
        Log.NORMAL.info("===========tenant-core init finish=======, buildTime={}", buildTime);
    }


}
